<script setup lang="ts">
import {shallowRef,nextTick, watch, ref ,defineComponent, defineEmits, toRefs} from 'vue'

import AMapLoader from '@amap/amap-jsapi-loader';
import {any, bool, integer, string} from 'vue-types'
import { ElRow, ElCol, ElInput } from 'element-plus'
import { onMounted } from 'vue';
let map = shallowRef(null);
defineComponent({
  components: {
    ElCol,
    ElRow,
    ElInput
  }
})
const emit = defineEmits(['sendposition'])

const props = defineProps({
    mapId:{
        type: string,
        default: () => 'mapBox' 
    },
    mapHeight:{
        type: string,
        default: () => '450px' 
    },
    positionList:{
        type: Array,
        default: () => [] 
    },
    address:{
        type: string,
        default: () => '' 
    },
    showInput:{
      type:bool,
      default: () => true
    },
})
const refprop = toRefs(props)

let mapText = ref('')
mapText.value = refprop.address.value

watch(
    () => props.mapId,
    () => {
        nextTick(()=>{
            initMap()
        })
    },
    {
        deep: true,
        immediate: true
    }
)

onMounted(()=>{
  initMap()
})

const initMap = ()=>{
   AMapLoader.load({
         key: "1a00aa60f1a54a6da80bd36f1c622bbe", // 申请好的Web端开发者Key，首次调用 load 时必填
         version: '1.4.2',
         plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.DistrictSearch', 'AMap.LngLat', 'AMap.Marker'],      // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap) => {
        map.value = new AMap.Map(props.mapId,{
            zoom: 12,
            center:[112.50018,34.67985],
            resizeEnable: true,
            title:'洛阳'
        });
        let marker;
        console.log("mapPositionList:", props.positionList);
          if(props.positionList.length > 1){
              marker = new AMap.Marker({
              position: props.positionList, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
              title: '瀍河'
            });
            // 将创建的点标记添加到已有的地图实例：
            map.value.add(marker);
            map.value.setFitView(marker);
          }
          let autocomplete = new AMap.Autocomplete({
            city: '洛阳',
            input: 'mapinput'
          });
          let placeSearch = new AMap.PlaceSearch({
            city: '洛阳',
            map: map
          });

          AMap.event.addListener(autocomplete, 'select', e => {
            let namer =e.poi.name
            let objposition = []
            
            if(e.poi.location){
              objposition = [e.poi.location?.lng, e.poi.location?.lat]
              if(marker){
                map.value.remove(marker);
              }
              marker = new AMap.Marker({
                position:objposition,
                offset: new AMap.Pixel(-10, -20)
              });
              map.value.add(marker);
              map.value.setFitView(marker);
            }
            
            placeSearch.setCity(e.poi.adcode);
            placeSearch.search(namer);
            emit('sendposition', {name:namer, position:objposition})
            console.log(e.poi,'e.poi')
          });
          // 搜索后自动生成的标记点击事件
          AMap.event.addListener(placeSearch, 'markerClick', e => {
            console.log(e, '456');
          });
          // 点击地图位置重新标记
          map.value.on('click', function (ev) {
            if(marker){
              map.value.remove(marker);
            }
            let objposition =  [ev.lnglat.lng, ev.lnglat.lat]
            let lnglat = ev.lnglat.lng + ',' + ev.lnglat.lat;
            marker = new AMap.Marker({
              position:objposition,
              offset: new AMap.Pixel(-10, -20)
            });
            map.value.add(marker);
            // 地图逆解析=>经纬度转地址详情
            AMap.plugin('AMap.Geocoder', function(){
              let geocoder = new AMap.Geocoder({
                city: '洛阳'
              });
              geocoder.getAddress(lnglat, function (status, result) {
                if (status === 'complete' && result.info === 'OK') {
                    mapText.value = result.regeocode.formattedAddress
                    emit('sendposition', {name:mapText.value, position:objposition})
                }
              });
            });
          });
        // 清除标记
        //   let clearMarkerButton = document.getElementById('clearMarkerButton');
        //   let clearMarkerFun = () => {
        //     mapText.value = '';
        //     map.value.clearMap();
        //   };
        //   AMap.event.addDomListener(clearMarkerButton, 'click', clearMarkerFun);
    }).catch(err=>{
        console.log(err)
    })
}

</script>

<template>
 <el-row :gutter="10" style="width:100%;">
    <el-col :span="24" v-if="showInput">
        <el-input id="mapinput" v-model="mapText" />
    </el-col>
    <el-col :span="24">
        <div :id="mapId" :style="{width: '100%', height: mapHeight}"></div>
    </el-col>
 </el-row>
   
</template>

<style>
    .amap-sug-result {
        z-index: 9999;
    }
</style>
